import { Actions, ActTypes } from './action';

export interface IUser {
    name: string
    isFixed: boolean // 是否是固定额度
    value: number   // 奖金额度
    coefficient: number // 奖金系数
    bonus: number
}

interface DataState {
    total: number // 奖金总额
    userList: IUser[]
}

interface UIState {
}

export type State = DataState & UIState;

const initialState: State = {
    total: 0,
    userList: []
};

export const reducer = (state: State = { ...initialState }, action: Actions): State => {
    switch (action.type) {
        case ActTypes.Clear: {
            return { ...initialState }
        }
        case ActTypes.AddUser: {
            // 先去重
            const userList = state.userList;
            const addUserList = action.payload.filter(name => !userList.find(u => u.name === name)).map(name => ({
                name, isFixed: false, value: 0, coefficient: 0.1, bonus: 0
            }));
            return { ...state, userList: [...state.userList, ...addUserList] }
        }
        case ActTypes.DelUser: {
            return { ...state, userList: state.userList.filter((u, index) => action.payload.indexOf(index) === -1) }
        }
        case ActTypes.ToggleIsFixed: {
            const userList = [...state.userList];
            const { index, isFixed } = action.payload;
            userList[index].isFixed = isFixed;
            return { ...state, userList }
        }
        case ActTypes.SetValue: {
            const userList = [...state.userList];
            const { index, value } = action.payload;
            userList[index].value = value;
            return { ...state, userList }
        }
        case ActTypes.SetCoefficient: {
            const userList = [...state.userList];
            const { index, coefficient } = action.payload;
            userList[index].coefficient = coefficient;
            return { ...state, userList }
        }
        case ActTypes.SetTotal: {
            return { ...state, total: action.payload }
        }
        default:
            return state
    }
};
